import MSData
import WorkerMSAPI
import WorkerMSDB
import MSLogger
import MSDBTemplates
import WorkerPCNFirebird

import time
import datetime
import os
import sys
import heartbeating
import pdb

MSLogger.logInit('C:\\safe\\ms.autester.log', 6, True)
MSLogger.logInfo('ms autotester started')
reader = WorkerMSDB.Worker('localhost', '2929', 'PGSMData', 'sa', 'safeinside')
reader.connect()

writer = WorkerPCNFirebird.Worker('192.168.0.121:C:\\pcn6\\data\\DATA.GDB', 'SYSDBA', 'masterkey')
writer.connect()

if os.path.exists('c:\\safe\\ms.autotester.pid'):
    MSLogger.logError('ms autotester already running')
    sys.exit()

f = open('c:\\safe\\ms.autotester.pid', 'w')
f.close()

cursor = reader.connection.cursor()
wcur = writer.connection.cursor()
td = datetime.timedelta(minutes=30)
try:
    lastevents = {}
    while True:
        objects = []
        MSDBTemplates.GET_MSObjects_FROM_CarOnline(reader.connection.cursor(), objects)
        for o in objects:
            try:
                query = 'SELECT TOP(1) id,eventTime,type FROM _event_data_internal WHERE deviceId=%s AND type=98 ORDER BY eventTime DESC' % (str(o.objectMSId))
                cursor.execute(query)
                d = cursor.fetchall()

                if not lastevents.has_key(o.objectMSId):
                    if len(d) > 0 and len(d[0]) == 3 and d[0][2] == 98:
                        #init first event
                        lastevents[o.objectMSId] = d[0][1]
                    #else - no any events at all
                else:
                    if len(d) > 0 and len(d[0]) == 3 and d[0][2] == 98:
                        if (d[0][1] <= lastevents[o.objectMSId]) or (datetime.datetime.fromtimestamp(time.time()) - d[0][1] > td):
                            #base case - offline
                            raw = reader.parseEventPGSM(d[0])
                            e = MSData.MSEvent()
                            e.fromPGSM_AUTOTEST(reader.parseEventPGSM(d[0]))
                            e.contactIdFull = 'auto'
                            e.contactIdType = '3551'
                            e.contactIdGroup = '00'
                            e.contactIdZona = '00'
                            e.objectId = o.objectPCNId
                            recId = MSDBTemplates.GET_LastRecId_FROM_sgn(wcur)
                            MSDBTemplates.STORE_MSEvent_TO_sgn(wcur, e, recId)
                            writer.connection.commit()
                        #normal case - store last event
                        lastevents[o.objectMSId] = d[0][1]

            except Exception, err:
                MSLogger.logError('object(%s:%s) error: %s' % (str(o.objectPCNId), str(o.objectMSId), str(err)))
                continue
        time.sleep(1800)
except KeyboardInterrupt:
    MSLogger.logError('ms checker stopped')
    os.unlink('c:\\safe\\ms.autotester.pid')
except Exception, err:
    MSLogger.logError('ms checker fatal error: %s' % (str(err)))
    os.unlink('c:\\safe\\ms.autotester.pid')
    
